package com.juku2024.juku.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.R
import com.juku2024.juku.adapter.DialogSourceListAdapter
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.model.PlayInfoResponse
import com.juku2024.juku.tools.AnalysisUtils
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.SPUtil
import com.juku2024.juku.tools.WrapLinearLayoutManager


class VideoSourceDialog(context: Context, style: Int = R.style.Down2UpDialogStyle): Dialog(context, style) {


    private var sourceId = 0
    private var isInit = false
    // 当前的视频id，如果相同的视频，不再充值adapter
    private var currentVideoId = 0L
    // 是否重置adapter
    private var isResetAdapter  = true
    private var listener: OnVideoSourceClickListener? = null
    private var sourcesList: ArrayList<PlayInfoResponse>? = null
    // 视频源adapter
    private val sourceAdapter by lazy { DialogSourceListAdapter(ArrayList()) }

    private var defaultTopSourceDialog: CommonDialog? = null

    private lateinit var recyclerSource: RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_video_source)

        val tvCancel = findViewById<TextView>(R.id.tvCancel)
        tvCancel.setOnClickListener {
            dismiss()
        }

        val topLayout = findViewById<View>(R.id.video_source_tip)
        topLayout.setOnClickListener {
            dismiss()
        }

        recyclerSource = findViewById(R.id.recyclerSource)
        recyclerSource.layoutManager = WrapLinearLayoutManager(context, RecyclerView.VERTICAL, false)
        recyclerSource.adapter = sourceAdapter
        sourceAdapter.setOnItemClickListener { _, _, position ->
            val item = sourceAdapter.getItem(position)
            if (item.id == sourceId) return@setOnItemClickListener
            sourceId = item.id
            listener?.onSourceClicked(item)
            dismiss()
        }
        isInit = true

        sourceAdapter.setOnItemChildClickListener { _, view, position ->
            val item = sourceAdapter.getItem(position)
//            if (item.id != sourceId) return@setOnItemChildClickListener
            if (view.id == R.id.btn_add_top_source) {
                if (defaultTopSourceDialog == null) {
                    defaultTopSourceDialog = CommonDialog(context)
                }
                val title: String
                val msg: String
                if (item.id == SPUtil.instance.defaultTopSource) {
                    title = "确认取消当前线路“置顶”么?"
                    msg = "取消“置顶”后，播放视频会按默认排序播放线路，其他剧也会同步设置。"
                } else {
                    title = "确认将当前线路“置顶”么？"
                    msg = "设置“置顶”后，播放视频会优先播放“置顶”的线路，其他剧也会同步设置。"
                }
                defaultTopSourceDialog?.showDialog(
                    title,
                    msg,
                    AppUtils.getString(R.string.confirm), {
                        defaultTopSourceDialog?.dismiss()
                        if (item.id == SPUtil.instance.defaultTopSource) {
                            SPUtil.instance.defaultTopSource = -1
                            AnalysisUtils.analysis(Constants.EVENT_TOP_SOURCE, Constants.KEY_SETTING_TOP_SOURCE, "取消置顶")
                        } else {
                            SPUtil.instance.defaultTopSource = item.id

                            AnalysisUtils.analysis(Constants.EVENT_TOP_SOURCE, Constants.KEY_SETTING_TOP_SOURCE, "置顶")
                            AnalysisUtils.analysis(Constants.EVENT_TOP_SOURCE, Constants.KEY_SETTING_TOP_SOURCE_ID, "置顶线路：" + AppUtils.getSourceName(item.id) +", 国家：" + SPUtil
                                .instance
                                .czIpCountry)
                        }

                        // 重新排序
                        val sourceList = sourceAdapter.data
                        // 如果让客户端排序，则需要按照剧集数多少排序
                        if (SPUtil.instance.videoSourceOrder) {
                            sourceList.sortByDescending {
                                return@sortByDescending it.episodes?.size ?: 0
                            }
                        }
                        // 先给所有线路赋值初始weight，从头到尾，以此递减
                        val sourceCount = sourceList.size
                        sourceList.forEachIndexed { index, playInfoResponse ->
                            playInfoResponse.weight = sourceCount - index
                        }

                        // 按照解析线路中的weight设置到线路中
                        val homeModel = NoteRoomUtils.getInstance().homeTabDao().query()
                        homeModel?.analysis?.filter { it.weight > 0 }?.forEach { parseSourceModel ->
                            val targetSource = sourceList.firstOrNull { it.id == parseSourceModel.sourceId }
                            if (targetSource != null) {
                                targetSource.weight = parseSourceModel.weight
                                targetSource.isRecommend = true
                            }
                        }

                        // 设置置顶线路的weight
                        val topSourceId = SPUtil.instance.defaultTopSource
                        if (topSourceId >= 0) {
                            val topSourceModel = sourceList.firstOrNull { it.id == topSourceId }
                            if (topSourceModel != null) {
                                topSourceModel.weight = 9999
                            }
                        }
                        sourceList.sortByDescending { it.weight }


                        sourceAdapter.setList(sourceList)

                        recyclerSource.post {
                            recyclerSource.scrollToPosition(0)
                        }

                        listener?.onSourceResorted()

                    },
                    AppUtils.getString(R.string.cancel), {
                        defaultTopSourceDialog?.dismiss()
                    }
                )
                defaultTopSourceDialog?.show()
            } else {
                if (item.id == sourceId) return@setOnItemChildClickListener
                sourceId = item.id
                listener?.onSourceClicked(item)
                dismiss()
            }
        }

        // 无需重置adapter
        if (!isResetAdapter) return

        initUI()
    }

    override fun onStart() {
        super.onStart()
        val dialogHeight = WindowManager.LayoutParams.MATCH_PARENT
        val dialogWight = WindowManager.LayoutParams.MATCH_PARENT
        window?.decorView?.setPadding(0, 0, 0, 0)
        val lp: WindowManager.LayoutParams? = window?.attributes
        lp?.width = dialogWight
        lp?.height = dialogHeight
        lp?.gravity = Gravity.BOTTOM
        window?.attributes = lp
        window?.setBackgroundDrawableResource(android.R.color.transparent)
    }


    fun setVideoSource(videoId: Long, sourceId: Int, sources: ArrayList<PlayInfoResponse>?){
        isResetAdapter = currentVideoId != videoId
        // 无需重置adapter
        if (!isResetAdapter) return
        this.sourceId = sourceId
        this.sourcesList = sources
        if (!isInit) return

        initUI()
    }

    private fun initUI(){
        // 处理置顶线路
//        val topSourceIdIndex = sourcesList?.indexOfFirst { it.id == SPUtil.instance.defaultTopSource }?:-1
//        if (topSourceIdIndex > 0) {
//            val topSource = sourcesList?.removeAt(topSourceIdIndex)
//            if (topSource != null) {
//                sourcesList?.add(0, topSource)
//            }
//        }
        sourceAdapter.sourceId = sourceId
        sourceAdapter.setList(sourcesList)
        recyclerSource.post {
            val targetPos = sourcesList?.indexOfFirst { it.id == sourceId }?:0
            recyclerSource.scrollToPosition(targetPos)
        }
    }

    interface OnVideoSourceClickListener{
        fun onSourceClicked(source: PlayInfoResponse)
        fun onSourceResorted()
    }

    fun setVideoSourceClickListener(listener: OnVideoSourceClickListener?) {
        this.listener = listener
    }


}